package dnl.dtools.grm.operations.io;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;

import de.schlichtherle.io.File;
import dnl.dtools.grm.Resource;
import dnl.dtools.grm.operations.ResourceOperationException;
import dnl.dtools.grm.operations.TargetBasedResourceOperation;
import dnl.logging.LightLog;

/**
 * 
 * @author daniel
 */
public class GenericCopyOperation extends TargetBasedResourceOperation {

	public GenericCopyOperation(Resource[] sources, Resource target) {
		super(sources, target);
	}

	public int getProgress() {
		return 0;
	}

	@Override
	public void operate() throws ResourceOperationException {
		// LocalFileSystemEntry r2 = (LocalFileSystemEntry) target;

		for (int i = 0; i < sources.length; i++) {
			// LocalFileSystemEntry r1 = (LocalFileSystemEntry) sources[i];
			boolean success = true;
			Resource t = target.getChild(sources[i].getName());

			
			try {
				InputStream is = sources[i].getInputStream();
				OutputStream os = t.getOutputStream();
				IOUtils.copy(is, os);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				success = false;
			}
			
			StringBuffer sb = new StringBuffer();
			sb.append(success ? "Success" : "Failure");
			sb.append(" copying from " + sources[i] + "  to  " + t);
			LightLog.debug(sb.toString());

			double d = (i+1) / sources.length;
			setProgress(d);
		}

	}

	public static void main(String[] args) {
		File f1 = new File(
				"/home/daniel/dloads/ganymed-ssh2-build209.zip/ganymed-ssh2-build209/ganymed-ssh2-build209.jar");
		File f2 = new File("/home/daniel/tmp/ganymed-ssh2-build209.jar");
		boolean b = f1.copyAllTo(f2);
		System.err.println(">> " + b);
	}

}
